﻿using UnityEngine;
using System.Collections;

public class MenuScript : MonoBehaviour 
{
    public GameObject persistentManager;
    public EezingMethod eezIn;
    public EezingMethod eezOut;

    private GUITextOrderer guiTextOrderer;
    private float timef = 0;
   
	void Start () 
    {
        guiTextOrderer = GetComponent<GUITextOrderer>();
	}	

	void Update () 
    {
        if (Input.GetMouseButtonDown(0) && gameObject.activeSelf && !persistentManager.GetComponent<PersistentManagerScript>().IsFading())
        {
            Close();
            persistentManager.GetComponent<PersistentManagerScript>().Fade(FadeDir.outF);           
        }

        if (guiTextOrderer.texts[1].gameObject.activeSelf)
            UpdatePressToPlay();
	}

    public void Open(float time)
    {
        timef = time;
        UpdateTexts();
        for (int i = 0; i < guiTextOrderer.texts.Count; i++)
        {
            persistentManager.GetComponent<Eezing>().EezIn(eezIn, guiTextOrderer.texts[i].gameObject, guiTextOrderer.GetTextFinalPos(i), Mathf.Abs(timef - 0.1f), 1.0f);
        }

        StartCoroutine("OpenPressToPlay");
    }

    public void Close()
    {
        for (int i = 0; i < guiTextOrderer.texts.Count; i++)
        {
            persistentManager.GetComponent<Eezing>().EezOut(eezOut, guiTextOrderer.texts[i].gameObject, guiTextOrderer.GetTextFinalPos(i), Mathf.Abs(timef - 0.1f), 1.0f);
        }

        guiTextOrderer.texts[1].gameObject.SetActive(false);
        StopCoroutine("OpenPressToPlay");
    }

    public void UpdateTexts()
    {
        if(guiTextOrderer == null)
            guiTextOrderer = GetComponent<GUITextOrderer>();
        guiTextOrderer.texts[2].text = "High Score: " + persistentManager.GetComponent<PersistentManagerScript>().GetMaxScore();
        guiTextOrderer.texts[3].text = "Recent Score: " + persistentManager.GetComponent<PersistentManagerScript>().GetRecentScore();       
    }

    private IEnumerator OpenPressToPlay()
    {
        yield return new WaitForSeconds(2.5f);
        guiTextOrderer.texts[1].gameObject.SetActive(true);
    }

    private void UpdatePressToPlay()
    {
        Color color = guiTextOrderer.texts[1].GetComponent<GUIText>().color;
        guiTextOrderer.texts[1].GetComponent<GUIText>().color = new Color(color.r, color.g, color.b, 0.1f + Mathf.Abs(Mathf.Sin(Time.timeSinceLevelLoad * 2)) / 1.25f);


    }
}
